package com.sk.security.provider.wechat;

import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @Author jiaok
 * @Date 2024-03-25 14:09
 */
@Data
@Slf4j
public class WechatAuthenticationProvider implements AuthenticationProvider {


    /**
     * 微信认证
     * @param authentication
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        WechatAuthenticationToken authenticationToken = (WechatAuthenticationToken) authentication;
        String loginCode = (String) authenticationToken.getPrincipal();
        String phoneCode = (String) authenticationToken.getPhoneCode();
        String env="test";
        String openid ="";
        if(env.equals("test")){
            openid="o3AXt4qYQKYe7YGBO_R2qH8YN708";
        }else{
            WeiXinLgoinVo weiXinLgoinVo= new WeiXinLgoinVo(loginCode,phoneCode);
            CommonResponse<WxLogin2Dto> responseDto = appletUserService.weixinLogin(weiXinLgoinVo);
            if(!responseDto.getCode().equals(ResponseCode.SUCCESS.getCode())){
                throw new WechatLoginException(responseDto.getCode(),responseDto.getMsg());
            }
            WxLogin2Dto wxLogin2Dto=responseDto.getData();
            openid = wxLogin2Dto.getOpenid();
        }
        UserDetails userDetails = ((WechatUserDetailsServiceImpl) userDetailsService).loadUserByOpenId(openid);
        WechatAuthenticationToken result = new WechatAuthenticationToken(userDetails, userDetails.getAuthorities());
        result.setDetails(authentication.getDetails());
        log.info("Authentication:{}", JSONObject.toJSON(result));
        return result;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
